package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"os"
	"strings"
	"tools/spiderpic"
)

var (
	g_sub_cmd      string = ""          //子命令
	g_sub_cmd_desc        = "spiderpic" //子命令显示
	g_h            bool   = false       //help信息
)

func main() {
	if argsProc() != nil {
		return
	}
	if g_sub_cmd == "" {
		fmt.Fprintf(os.Stderr, "请输入子命令\n")
		return
	}
	//clean
	bufio.NewReader(os.Stdin)
	//开户个shell方便后台命令控制
	shellProc()
}

func argsProc() error {
	cmd := flag.NewFlagSet("main", flag.ExitOnError)
	cmd.StringVar(&g_sub_cmd, "sub_cmd", "", "子命令: "+g_sub_cmd_desc)
	cmd.BoolVar(&g_h, "h", false, "帮助信息")
	cmd.BoolVar(&g_h, "H", false, "帮助信息")
	cmd.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of param:\n")
		cmd.PrintDefaults()
		return
	}
	cmd.Parse(os.Args[1:])
	if g_h {
		cmd.Usage()
		return errors.New("help")
	}

	return nil
}

func shellProc() {
	reader := bufio.NewReader(os.Stdin)

	for {
		fmt.Print("> ")
		input, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println(err)
			continue
		}
		err = inputProc(input)
		if err != nil {
			fmt.Println(err)
		}
	}
}

func inputProc(input string) error {
	input = strings.TrimSuffix(input, "\n")
	input = strings.TrimSpace(input)

	args := strings.Split(input, " ")
	if len(args) == 0 {
		return nil
	}

	cmd := string(args[0])
	switch cmd {
	case "spiderpic":
		fmt.Println("recv spiderpic")
	case "quit":
		os.Exit(0)
	default:
		fmt.Println("err cmd")
	}

	return nil
}
